package com.lw.leetcode.tree.b;

import com.lw.leetcode.tree.TreeNode;

/**
 * 654. 最大二叉树
 *
 * @Author liw
 * @Date 2021/5/12 14:00
 * @Version 1.0
 */
public class ConstructMaximumBinaryTree {

    public TreeNode constructMaximumBinaryTree(int[] nums) {
        if (nums == null || nums.length == 0) {
            return null;
        }
        return find(nums, 0, nums.length - 1);
    }

    private TreeNode find (int[] arr, int st, int end) {
        if (st > end) {
            return null;
        }
        int max = arr[st];
        int index = st;
        for (int i = st + 1; i <= end; i++) {
            if (arr[i] > max) {
                max = arr[i];
                index = i;
            }
        }
        TreeNode node = new TreeNode(max);
        node.left = find(arr, st, index - 1);
        node.right = find(arr, index + 1, end);
        return node;
    }

}
